<template>
  <div>
    <!-- 面包屑功能-眉角导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 下边是白色的背景,所以是cart标签 -->
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon>
      </el-alert>
      选择商品分类:<el-cascader v-model="selectVal" :options="options"
                   :props='cateProps' clearable @change="chgCate">
      </el-cascader>
      <el-tabs v-model="activeName" @tab-click='chgCate'>
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 disabled ===true的时候会被禁掉 -->
          <el-button type="primary" @click="dialogFormVisibleAdd=true"
                     :disabled='selectVal.length!==3'>添加参数
          </el-button>
          <!-- 表格 -->
          <el-table :data="manyData" border style="width: 100%">
            <el-table-column type="expand" label="展开" width="50">
              <!-- 用插槽来获取数据 closable 显示 -->
              <template slot-scope="scope">
                <el-tag v-for="(item ,i) in scope.row.attr_vals" :key="i"
                        closable @close='delAttr(scope.row,i)'>
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue" ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <el-button type="primary" size="mini" icon="el-icon-edit">
                编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete">
                删除</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态配置" name="only">
          <el-button type="primary" :disabled='selectVal.length!==3'>添加属性
          </el-button>
          <el-table :data="onlyData" border style="width: 100%">
            <el-table-column type="expand" label="展开" width="50">
              <!-- 用插槽来获取数据 -->
              <template slot-scope="scope">
                <el-tag v-for="(item ,i) in scope.row.attr_vals" :key="i"
                        closable>
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue" ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <el-button type="primary" size="mini" icon="el-icon-edit">
                编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete">
                删除</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 动态参数dielog -->
    <el-dialog title="添加用户" class="mydialog"
               :visible.sync="dialogFormVisibleAdd">
      <el-form ref="attrFormRef" :model="addForm" :rules="rules"
               label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="attrFormSubmit">确 定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 页面一加载的时候,就应该触发方法,获取数据
  mounted () {
    this.getCateList()
  },
  data () {
    return {
      /* 添加参数的数据 */
      dialogFormVisibleAdd: false,
      addForm: {
        attr_name: ""
      },
      rules: {
        attr_name: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
        ]
      },
      /* 表格的数据 */
      manyData: [],
      onlyData: [],
      // 默认显示的标签页
      activeName: 'many',
      // 级联选择器需要的参数
      cateProps: {
        // true可以选择父级
        checkStrictly: false,
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      options: [],
      selectVal: [],
    }
  },
  methods: {
    async delAttr (row, i) {
      // pop删除末尾 shfit删除开头
      // 删除需要2个删除的位置下标,删除几个,[添加的数据,]
      row.attr_vals.splice(i, 1)
      this.save_attr(row)
    },
    handleInputConfirm (row) {
      //             tag的内容      某行属性的id    分类的id          分类名           动态还是静态        tag的数组
      // console.log(row.inputValue, row.attr_id, this.selectVal[2], row.attr_name, this.activeName, row.attr_vals)
      // 先校验数据,不能是空格 0 null undefined默认是false
      if (!row.inputValue.trim()) {
        // 添加完成需要清空输入框的数据
        row.inputValue = ''
        row.inputVisible = false;
        return
      }
      // 先放到数组里边
      row.attr_vals.push(row.inputValue)
      this.save_attr(row, '添加失败', '添加成功')
    },
    // es6方法赋默认值
    async save_attr (row, errormsg = '操作失败', successmsg = '操作成功') {
      const { data: { meta } } = await this.$axios.put(`categories/${this.selectVal[2]}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(" ") })
      if (meta.status !== 200) {
        return this.$message.error(errormsg)
      }
      // 添加完成需要清空输入框的数据
      row.inputValue = ''
      row.inputVisible = false;
      return this.$message.success(successmsg)
    },
    showInput (row) {
      row.inputVisible = true;
      // 组件渲染之后会自动调用的方法
      this.$nextTick(_ => {
        // 让saveTagInput 获取到了焦点
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 添加参数的提交的方法
    attrFormSubmit () {
      this.$refs.attrFormRef.validate(async (valid) => {
        // 如果出错
        if (!valid) {
          return this.$message.error("请检查填写的数据")
        }
        // console.log(this.selectVal, this.activeName, this.addForm.attr_name)
        const { data: { meta } } = await this.$axios.post(`categories/${this.selectVal[2]}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (meta.status !== 201) {
          return this.$message.error("保存参数失败")
        }
        // 重新渲染页面,
        this.getParms();
        // 关闭diolog
        this.dialogFormVisibleAdd = false;
        // console.log(data, meta)
      })
    },
    // 标签页的点击事件
    tabClick () {
      this.getParms();
      // 可以直接调用
      // this.chgCate()
    },
    // 级联,值改变了,
    chgCate () {
      this.getParms();
    },
    async getParms () {
      const length = this.selectVal.length
      if (length !== 3) {
        this.selectVal = []
        return this.$message.error("请先选择分类")
      }
      const { data: { data, meta } } = await this.$axios.get(`categories/${this.selectVal[2]}/attributes`, { params: { sel: this.activeName } })
      console.log(data, meta)
      if (meta.status !== 200) {
        return this.$message.error('获取配置信息失败')
      }
      // 修改data里边的数据
      data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
        // 添加2个属性,控制table的属性
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === "many") {
        this.manyData = data
      } else {
        this.onlyData = data
      }
    },
    async getCateList () {
      // this.$axios.get('categories', { params: { type: 3 } })
      const { data: { data, meta } } = await this.$axios.get('categories')
      console.log(data, meta)
      // 说明数据右问题
      if (meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.options = data
    }
  }
}
</script>

<style lang="css" scoped>
.box-card {
  text-align: left;
}
.el-tag,
.button-new-tag,
.input-new-tag {
  margin-left: 20px;
}
.input-new-tag {
  width: 200px;
}
</style>